<template>
  <div class="utils-demo">
    <h1>工具函数演示</h1>
    <p>Vue Toolkit 提供的实用工具函数展示</p>

    <!-- 格式化工具演示 -->
    <section class="demo-section">
      <h2>格式化工具</h2>
      <div class="demo-content">
        <div class="demo-preview">
          <!-- 数字格式化 -->
          <div class="demo-input">
            <label>数字格式化：</label>
            <input 
              v-model.number="numberInput" 
              type="number" 
              placeholder="请输入数字" 
            />
            <p><strong>千分位格式：</strong>{{ formattedNumber }}</p>
            <p><strong>货币格式：</strong>{{ formattedCurrency }}</p>
            <p><strong>百分比格式：</strong>{{ formattedPercent }}</p>
          </div>

          <!-- 日期格式化 -->
          <div class="demo-input">
            <label>日期格式化：</label>
            <input 
              v-model="dateInput" 
              type="datetime-local" 
            />
            <p><strong>标准格式：</strong>{{ formattedDate }}</p>
            <p><strong>自定义格式：</strong>{{ formattedDateCustom }}</p>
            <p><strong>相对时间：</strong>{{ relativeTime }}</p>
          </div>

          <!-- 文件大小格式化 -->
          <div class="demo-input">
            <label>文件大小格式化：</label>
            <input 
              v-model.number="fileSizeInput" 
              type="number" 
              placeholder="请输入字节数" 
            />
            <p><strong>格式化结果：</strong>{{ formattedFileSize }}</p>
          </div>
        </div>
        
        <div class="demo-code">
          <h4>代码示例</h4>
          <pre><code>{{ formatCode }}</code></pre>
        </div>
      </div>
    </section>

    <!-- 验证工具演示 -->
    <section class="demo-section">
      <h2>验证工具</h2>
      <div class="demo-content">
        <div class="demo-preview">
          <!-- 邮箱验证 -->
          <div class="demo-input">
            <label>邮箱验证：</label>
            <input 
              v-model="emailInput" 
              placeholder="请输入邮箱地址" 
            />
            <p :class="{ valid: isValidEmail, invalid: !isValidEmail && emailInput }">
              {{ emailInput ? (isValidEmail ? '✓ 邮箱格式正确' : '✗ 邮箱格式错误') : '请输入邮箱地址' }}
            </p>
          </div>

          <!-- 手机号验证 -->
          <div class="demo-input">
            <label>手机号验证：</label>
            <input 
              v-model="phoneInput" 
              placeholder="请输入手机号" 
            />
            <p :class="{ valid: isValidPhone, invalid: !isValidPhone && phoneInput }">
              {{ phoneInput ? (isValidPhone ? '✓ 手机号格式正确' : '✗ 手机号格式错误') : '请输入手机号' }}
            </p>
          </div>

          <!-- 身份证验证 -->
          <div class="demo-input">
            <label>身份证验证：</label>
            <input 
              v-model="idCardInput" 
              placeholder="请输入身份证号" 
            />
            <p :class="{ valid: isValidIdCard, invalid: !isValidIdCard && idCardInput }">
              {{ idCardInput ? (isValidIdCard ? '✓ 身份证号格式正确' : '✗ 身份证号格式错误') : '请输入身份证号' }}
            </p>
          </div>

          <!-- URL验证 -->
          <div class="demo-input">
            <label>URL验证：</label>
            <input 
              v-model="urlInput" 
              placeholder="请输入URL地址" 
            />
            <p :class="{ valid: isValidUrl, invalid: !isValidUrl && urlInput }">
              {{ urlInput ? (isValidUrl ? '✓ URL格式正确' : '✗ URL格式错误') : '请输入URL地址' }}
            </p>
          </div>

          <!-- 密码强度验证 -->
          <div class="demo-input">
            <label>密码强度：</label>
            <input 
              v-model="passwordInput" 
              type="password" 
              placeholder="请输入密码" 
            />
            <p :class="strengthClass">
              {{ passwordStrengthText }}
            </p>
          </div>

          <!-- 综合验证 -->
          <div class="demo-input">
            <label>综合验证（用户名）：</label>
            <input 
              v-model="usernameInput" 
              placeholder="2-20个字符，字母数字下划线" 
            />
            <div class="validation-result">
              <p v-if="usernameValidation.valid" class="valid">
                ✓ 用户名格式正确
              </p>
              <div v-else-if="usernameInput">
                <p v-for="error in usernameValidation.errors" :key="error" class="invalid">
                  ✗ {{ error }}
                </p>
              </div>
              <p v-else>请输入用户名</p>
            </div>
          </div>
        </div>
        
        <div class="demo-code">
          <h4>代码示例</h4>
          <pre><code>{{ validationCode }}</code></pre>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { 
  formatNumber, 
  formatDate, 
  formatFileSize, 
  formatCurrency, 
  formatPercent,
  isEmail, 
  isPhone, 
  isIdCard, 
  isUrl,
  getPasswordStrength,
  validate
} from 'vue-toolkit/lib/utils'

// 格式化工具状态
const numberInput = ref(1234567.89)
const dateInput = ref(new Date().toISOString().slice(0, 16))
const fileSizeInput = ref(1048576)

// 验证工具状态
const emailInput = ref('')
const phoneInput = ref('')
const idCardInput = ref('')
const urlInput = ref('')
const passwordInput = ref('')
const usernameInput = ref('')

// 格式化计算属性
const formattedNumber = computed(() => {
  return formatNumber(numberInput.value, { useGrouping: true })
})

const formattedCurrency = computed(() => {
  return formatCurrency(numberInput.value)
})

const formattedPercent = computed(() => {
  return formatPercent(numberInput.value / 100)
})

const formattedDate = computed(() => {
  return formatDate(dateInput.value)
})

const formattedDateCustom = computed(() => {
  return formatDate(dateInput.value, 'YYYY-MM-DD HH:mm:ss')
})

const relativeTime = computed(() => {
  const now = new Date()
  const target = new Date(dateInput.value)
  const diff = target.getTime() - now.getTime()
  const days = Math.round(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) return '今天'
  if (days === 1) return '明天'
  if (days === -1) return '昨天'
  if (days > 0) return `${days}天后`
  return `${Math.abs(days)}天前`
})

const formattedFileSize = computed(() => {
  return formatFileSize(fileSizeInput.value)
})

// 验证计算属性
const isValidEmail = computed(() => {
  return emailInput.value ? isEmail(emailInput.value) : false
})

const isValidPhone = computed(() => {
  return phoneInput.value ? isPhone(phoneInput.value) : false
})

const isValidIdCard = computed(() => {
  return idCardInput.value ? isIdCard(idCardInput.value) : false
})

const isValidUrl = computed(() => {
  return urlInput.value ? isUrl(urlInput.value) : false
})

const passwordStrength = computed(() => {
  return passwordInput.value ? getPasswordStrength(passwordInput.value) : 'weak'
})

const passwordStrengthText = computed(() => {
  if (!passwordInput.value) return '请输入密码'
  
  const strengthMap = {
    weak: '弱',
    medium: '中等',
    strong: '强'
  }
  
  return `密码强度：${strengthMap[passwordStrength.value]}`
})

const strengthClass = computed(() => {
  return {
    valid: passwordStrength.value === 'strong',
    invalid: passwordStrength.value === 'weak' && passwordInput.value
  }
})

const usernameValidation = computed(() => {
  if (!usernameInput.value) {
    return { valid: false, errors: [] }
  }
  
  const rules = [
    { required: true, message: '用户名不能为空' },
    { minLength: 2, message: '用户名长度不能少于2个字符' },
    { maxLength: 20, message: '用户名长度不能超过20个字符' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' }
  ]
  
  return validate(usernameInput.value, rules)
})

// 代码示例
const formatCode = `import { formatNumber, formatDate, formatFileSize } from 'vue-toolkit'

// 数字格式化
formatNumber(1234567.89, { useGrouping: true })  // "1,234,567.89"

// 货币格式化
formatCurrency(1234.56)  // "¥1,234.56"

// 日期格式化
formatDate(new Date())  // "2024/01/01"
formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')  // "2024-01-01 12:00:00"

// 文件大小格式化
formatFileSize(1048576)  // "1.00 MB"`

const validationCode = `import { isEmail, isPhone, validate } from 'vue-toolkit'

// 基础验证
isEmail('user@example.com')  // true
isPhone('13800138000')  // true

// 综合验证
const rules = [
  { required: true, message: '不能为空' },
  { minLength: 2, message: '长度不能少于2个字符' },
  { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母数字下划线' }
]

const result = validate('username', rules)
// { valid: true, message: undefined, errors: [] }`
</script>

<style scoped>
.utils-demo h1 {
  color: #2c3e50;
  margin-bottom: 0.5rem;
}

.utils-demo > p {
  color: #7f8c8d;
  font-size: 1.1rem;
  margin-bottom: 3rem;
}

.demo-input {
  margin-bottom: 2rem;
  padding: 1.5rem;
  background-color: #fafafa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.demo-input label {
  display: block;
  margin-bottom: 0.8rem;
  font-weight: 600;
  color: #495057;
  font-size: 1rem;
}

.demo-input input {
  width: 100%;
  max-width: 400px;
  padding: 0.75rem;
  border: 2px solid #dee2e6;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.2s ease;
}

.demo-input input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}

.demo-input p {
  margin-top: 0.8rem;
  margin-bottom: 0.4rem;
  font-size: 0.95rem;
  font-weight: 500;
}

.validation-result p {
  margin-top: 0.5rem;
  margin-bottom: 0.3rem;
}

.valid {
  color: #28a745;
}

.invalid {
  color: #dc3545;
}

.demo-code h4 {
  margin-top: 0;
  margin-bottom: 1rem;
  color: #495057;
  font-size: 1.1rem;
  font-weight: 600;
}
</style>